#include "servermessageadapter.h"
ServerMessageAdapter * ServerMessageAdapter::server_msg_adapter = nullptr;
ServerMessageAdapter::ServerMessageAdapter(QObject *parent) : QObject(parent)
{
    connect(TCPSocket::getInstance(),SIGNAL(readyRead()),this,SLOT(solveServerMessage()));

}
void ServerMessageAdapter::run()
{
    qDebug()<<"server message thread id "<<QThread::currentThreadId();
    while(true)
    {
        getServerMessage();
        solveServerMessage();
    }
}
void ServerMessageAdapter::setSocket(TCPSocket* _socket)
{

}
int ServerMessageAdapter::getServerMessage()
{
//    qDebug()<<"get server message in id: "<<QThread::currentThreadId();
    return 0;

}
void ServerMessageAdapter::solveServerMessage()
{
        qDebug()<<"get message from server";
        QByteArray data ;

        TCPSocket::getInstance()->myRead(data);
        qDebug()<<"datalen :"<<data.size();
        QJsonParseError json_error;
        QJsonDocument jsonDoc(QJsonDocument::fromJson(data, &json_error));
        if(json_error.error != QJsonParseError::NoError){

            qDebug() << "json error!";
            return;
        }

        QJsonObject rootObj = jsonDoc.object();
        QString type = rootObj["Type"].toString();
        qDebug() << "type: " << type;
        QStringList keys = rootObj.keys();
        for(int i=0;i<keys.count();i++)
        {
            qDebug()<<"Key "<<keys[i];
        }
        qDebug()<<"获取到的实际Json文件 :"<<rootObj;


        if(type == "REIGSTER_RES")
        {
            QString uid_me = rootObj["uid"].toString();
            emit sig_REIGSTER_RES(uid_me);
        }
        if(type == "LOGIN_RES")
        {
            QString status = rootObj["Status"].toString();
            if(status == "LoginSucess")
            {
                 emit sig_LOGIN_SUCCESS(true);
                 QString name = rootObj["name"].toString();
                 QString uid = rootObj["uid"].toString();
                 QString passwd = rootObj["passwd"].toString();
                 emit sig_LOGIN_INFO(name,uid,passwd);
            }
            if(status =="LoginFail")
            {
                emit sig_LOGIN_SUCCESS(false);
            }
            if(status =="ipError")
            {

            }

        }
        if(type =="MSG_SYNC")
        {
            int msg_num = rootObj["MSG_NUM"].toInt();

            QList<QPair<QString,QString>> msg_list;
            QString gid = rootObj["GID"].toString();
            for(int i=0;i<msg_num;i++)
            {

                QString msg_pak = rootObj["MSG"+QString::number(i)].toString();
                QJsonDocument doc = QJsonDocument::fromJson(msg_pak.toUtf8());
                QJsonObject obj = doc.object();
                QString msg = obj["msg"].toString();
                QString uid = obj["UID"].toString();
                msg_list.push_back(QPair<QString,QString>(uid,msg));
                qDebug()<<"msg sync :"<<msg;
            }
            emit sig_MSG_SYNC(gid,msg_list);
        }
        if(type =="LIST_SYNC")
        {
            qDebug()<<"大包"<<rootObj;
            int list_num = rootObj["LIST_NUM"].toInt();
            qDebug()<<"list num :"<<list_num;
            QList<QString> ass_info_list;

            for(int i=0;i<list_num;i++)
                ass_info_list.push_back(rootObj["LIST"+QString::number(i)].toString());
            QJsonDocument doc;
            for(int i=0;i<list_num;i++)
            {
                doc = QJsonDocument::fromJson(ass_info_list[i].toUtf8());
                QJsonObject obj = doc.object();
                qDebug()<<ass_info_list[i].toUtf8();
                QString id = obj["GID"].toString();
                qDebug()<<"gid"<<id;
                bool is_group = obj["isgroup"].toBool();
                Association ass(id);

                QJsonArray Usr_info_list = obj["USR_LIST"].toArray();
                qDebug()<<"info list"<<Usr_info_list;
                qDebug()<<"usr_info num:"<<Usr_info_list.size();
                for(int i=0;i<Usr_info_list.size();i++)
                {

                    QJsonDocument doc_2 = QJsonDocument::fromJson(Usr_info_list[i].toString().toUtf8());
                    qDebug()<<"   ..."<<doc_2.object()["name"].toString();
                    QString id =doc_2.object()["uid"].toString();
                    QString name =doc_2.object()["name"].toString();
                    ass.addUsr(name,id);
                    qDebug()<<"uid: "<<id<<" name: "<<name;



                }
                if(is_group)
                {
                    Account::getInstance()->setGroup(ass);
                }
                else
                {
                    Account::getInstance()->setFriend(ass);
                }

//                QJsonArray arry = doc_2.array();
//






            }

            emit sig_LIST_SYNC();

        }
        if(type== "MSG_UPDATE")
        {
            qDebug()<<rootObj;

            QString msg_pak = rootObj["MSG0"].toString();
            QString gid = rootObj["GID"].toString();
            bool is_group = rootObj["is_group"].toBool();
            QJsonDocument doc = QJsonDocument::fromJson(msg_pak.toUtf8());
            QJsonObject obj = doc.object();
            QString msg = obj["msg"].toString();
            QString uid = obj["UID"].toString();
            qDebug()<<"msg update: "<<msg;
            if(!is_group)
                emit sig_MSG_ACC(uid,msg);
            else
                emit sig_MSG_ACC(gid,uid,msg);
        }
        if(type =="POST_SYNC")
        {
            int list_num = rootObj["LIST_NUM"].toInt();
            for(int i=0;i<list_num;i++)
            {
                QString msg_pak = rootObj["LIST"+QString::number(i)].toString();
                qDebug()<<"list0 :"<<msg_pak;
                QJsonDocument doc = QJsonDocument::fromJson(msg_pak.toUtf8());
                QJsonObject obj =doc.object();

                QString gid_apply = obj["GID"].toString();
                QString uid_creater = obj["uid_adder"].toString();

                Account::getInstance()->insertPost(uid_creater,gid_apply);

            }
            if(list_num!=0)
                emit sig_POST_SYNC();
        }

//        for(int i = 0; i < keys.size(); i++){

//            if(i == 0)

//            else
//                qDebug() << "key" << i << " is:" << keys.at(i) << rootObj.value(keys.at(i)).toInt();
//        }

}
void ServerMessageAdapter::msgToJson(const QJsonObject& obj)
{
    QJsonDocument jsonDocument;
    jsonDocument.setObject(obj);
    QByteArray dataArray = jsonDocument.toJson();
//    qDebug()<<"before TCP write";
    TCPSocket::getInstance()->myWrite(dataArray);

//    qDebug()<<"after TCP write";

}
void ServerMessageAdapter::sendMessage(Package::LoginRequestSend login_package)
{
        qDebug()<<"sendMessage loginRequest";
        //make a Json data
        QJsonObject pageObject;
        pageObject.insert("Type","LOGIN");
        pageObject.insert("uid",login_package.uid_me);
        pageObject.insert("passwd",login_package.passwd);
        pageObject.insert("CHECK_NUM","1");
        pageObject.insert("IP","10.10.10.10");

        msgToJson(pageObject);



}

void ServerMessageAdapter::sendMessage(Package::RegisterRequestSend package)
{
        qDebug()<<"sendMessage RegisterRequest";
        QJsonObject pageObject;
        pageObject.insert("Type","RIGSTER");
        pageObject.insert("name",package.name);
        pageObject.insert("passwd",package.passwd);
        pageObject.insert("IP","10.10.10.10");
        pageObject.insert("PhoneNumber",package.phone_num);
        pageObject.insert("CHECK_NUM",package.check_str);

        msgToJson(pageObject);
}

void ServerMessageAdapter::sendMessage(Package::ChecknumRequestSend package)
{
    qDebug()<<"sendMessage ChecknumRequestSend";
    QJsonObject pageObject;
    pageObject.insert("Type","CHECK");
    pageObject.insert("phone",package.phone_num);

    msgToJson(pageObject);

}

void ServerMessageAdapter::sendMessage(Package::AddAssociationSend package)
{
        qDebug()<<"sendMessage AddAssociationSend";
        QJsonObject pageObject;
        pageObject.insert("Type","CREATE_GROUP");
        pageObject.insert("isgroup",package.isGroup);
        pageObject.insert("uid",package.uid_me);
        pageObject.insert("list_num",package.uid_friends.count());
        for(int i=0;i<package.uid_friends.count();i++)
            pageObject.insert("Friend",package.uid_friends.at(i));
        msgToJson(pageObject);
}


void ServerMessageAdapter::sendMessage(Package::InfoSyncRequestSend package)
{
        qDebug()<<"sendMessage InfoSyncRequestSend";
        QJsonObject pageObject;
        pageObject.insert("Type","LIST_SYNC");
        QString uid_me;
        Account::getInstance()->getMyUid(uid_me);
        pageObject.insert("uid",uid_me);

        msgToJson(pageObject);
}

void ServerMessageAdapter::sendInfoSyncMessage()
{
    Package::InfoSyncRequestSend package;
    sendMessage(package);
}
void ServerMessageAdapter::sendMessage(Package::MessageHistoryRequestSend package)
{
        qDebug()<<"sendMessage MessageHistoryRequestSend";
        QJsonObject pageObject;
        pageObject.insert("Type","MSG_SYNC");
        pageObject.insert("GID",package.uid_group_request);

        msgToJson(pageObject);

}
void ServerMessageAdapter::sendMessage(Package::MessageSend package)
{
    qDebug()<<"sendMessage MessageSend";
    QJsonObject pageObject;
    pageObject.insert("Type","MSG_SEND");
    pageObject.insert("UID",package.uid_me);
    pageObject.insert("GID",package.uid_group);
    pageObject.insert("msg",package.msg);

    msgToJson(pageObject);
}
void ServerMessageAdapter::sendMessage(Package::AddFriendRequestSend package)
{
    qDebug()<<"sendMessage AddFriend";

    QJsonObject pageObject;
    pageObject.insert("Type","APPLY_FRIEND");
    pageObject.insert("uid_friend",package.uid_friend);
    pageObject.insert("uid",package.uid_me);

    msgToJson(pageObject);

}
void ServerMessageAdapter::sendMessage(Package::AgreeToGroupStatus package)
{
    qDebug()<<"sendMessage agree to group status";

    QJsonObject obj;
    obj.insert("Type","AGREE_GROUP");
    obj.insert("UID",package.uid_friend_invate);
    obj.insert("GID",package.gid_invate);
    obj.insert("STATUS",package.is_agree);

    msgToJson(obj);
}
void ServerMessageAdapter::sendMessage(Package::AgreeToAddFriendStatus package)
{
    qDebug()<<"sendMessage agree to friend";

    QJsonObject obj;
    obj.insert("Type","ADD_FRIEND");
    obj.insert("UID",package.uid_friend);
    obj.insert("STATUS",package.is_agree);

    msgToJson(obj);

}
void ServerMessageAdapter::sendMessage(Package::CreateGroup)
{
    qDebug()<<"sendMessage create a group";

    QJsonObject obj;
    obj.insert("Type","CREATE_GROUP");

    msgToJson(obj);
}
